<template>
  <div>
    <!--     规格选择器 -->
    <SkuSelector
      :spu-id="spuId"
      :show-sku.sync="showSku"
      :is-alive="1"
      @skuBuy="skuBuy"
      :aliveInfo="aliveInfo"
      :aliveId="aliveInfo.alive_id"
      :hasPreferentialPrice="hasPreferentialPrice"
      :isCOPGoods="isCOPGoods"
      :getContainer="getContainer"
    ></SkuSelector>

    <confirm-order
      v-bind="initInfo"
      @successCallback="successCallback"
      @failCallback="failCallback"
      :boxshow.sync="showConfirmOrder"
      :baseInfoQuery.sync="baseInfoQuery"
      :goodsMsg="true"
      :aliveInfo="aliveInfo"
      :useScatter="useScatter"
      :confirmOrderPosition="confirmOrderPosition"
      :miniprogramSdkPaySetting="miniprogramSdkPaySetting"
      :getContainer="getContainer"
    ></confirm-order>

    <!--     支付完成-->
    <PayComplete
      :boxshow.sync="showPayComplete"
      :baseInfoQuery.sync="payCompleteQuery"
      :getContainer="getContainer"
      @payComplete="payComplete"
    ></PayComplete>
  </div>
</template>
<script>
import { request } from "@xiaoe/js-tools/lib/request";
import locale from '../../../mixins/locale'
import {isMP, isMiniProgramSdk, isAndroid, isIos, isELearnApp} from "../utils/checkEnv";
import { getMiniprogramSdkPaySetting} from "../fetch-data";
import { HANDLE_ORDER, COMMON_ERROR_MSG } from '../constants';
import { getOrderCache, clearOrderCache, debounce } from "../utils";
import { PayBackHandler } from '../strategy/pay-back-handler.js';
import { LogLevel, LogType } from "@xiaoe/skynet";

// import cloneDeep from "lodash/cloneDeep";
import {anonyLogon} from "@xiaoe/spark";
import { Toast, Dialog } from "vant";
import { jumpTool, urlConcatParams } from '@xiaoe/h5-jump-fe';
import ConfirmOrder from "./confirmOrder/index.vue";
import SkuSelector from "../../c-sku-selector/index.vue";
import PayComplete from "./PayComplete/index.vue";
import {
  COP_GOODS,
  IOS_MINIPROGRAM_DISPLAY_TYPE
} from "../constants/constant.js";
import {sensorsTrackButton} from "../utils/sensors_report";
// 小程序SDK支付开关
const MINIPROGRAM_SDK_PAY_SETTING = {
  OFF: 0, // 0: 关闭支付
  ON: 1 // 1: 开启支付
}

const SPU_TYPE = {
  1: "ITX",
  2: "ADO",
  3: "VDO",
  4: "ALV",
  5: "MMB",
  6: "SPC",
  7: "CMN",
  8: "BSC",
  9: "ATV",
  20: "EBK",
  25: "TCP",
  29: "OLC",
  21: "ENT",
  35: "BTK",
  41: "VCP",
  42: "OLP",
  45: "ALC",
  23: "SVP",
  68: "SRV",
  16: "PCD",
  50: "EKC",
};
// 新直播当页支付页面 - 目前只有微信环境使用
export default {
  name: "owgLivePay",
  components: {
    ConfirmOrder,
    SkuSelector,
    PayComplete,
  },
  mixins: [locale],
  data() {
    return {
      spuId: "",
      showSku: false,
      sheetInfo: {
        // 确认订单弹框配置信息
        title: this.t('confirmOrder_confirm_order'),
        showClose: true,
        showBack: false,
      },
      showCreateOrderView: true,
      isAndroid: isAndroid(),
      // 小程序SDK支付设置
      miniprogramSdkPaySetting: {
        paymentSwitch: MINIPROGRAM_SDK_PAY_SETTING.OFF, // 支付开关 0: 关闭, 1: 开启
        paymentPageUrl: '',  // 小程序页面路径
        fetchEnd: false,
      },
      showConfirmBox: false,
      baseInfoQuery: {},
      baseData: {
        baseInfo: null,
        shopConfInfo: {},
        featureInfo: null,
        confirmDetail: null,
        goodsInfo: {},
        activityInfo: null,
        svipInfo: null,
        goodsPackage: null,
        cartInfo: {},
        isSupportCoin: null,
        coinInfo: null,
      },
      goodsItem: {},  // 商品信息
      categoryInfo: [], // 分类信息
      hasPreferentialPrice: false, //需要领券
      isFromLiveGoodsList: false, // 是否从直播商品列表进入
      isToDetails: false, // 是否跳转到详情页
      permission: false,//免费领取按钮-有权益
      checkPrice: () => {}, // 是否需要检查价格
      showConfirmOrder:false,
      showPayComplete:false,
      // 支付完成页传参
      payCompleteQuery: {},
      useScatter:false,
      alive_sub_id:''
    }
  },
  props: {
    open: false,
    isLiveH5: {
      type: Boolean,
      default: true
    },
    aliveInfo: {
      type: Object,
      default: () => ({})
    },
    isGrayMarketing: {
      type: Boolean,
      default: false
    },
    // appen的dom
    getContainer: {
      type: String,
      default: 'body'
    },
    // 确认订单弹窗位置
    confirmOrderPosition: {
      type: String,
      default: 'bottom'
    }
  },
  computed: {
    popupOpen: {
      get() {
        return this.open;
      },
      set(val) {
        this.$emit("update:open", val);
      }
    },
    initInfo() {
      return {
        // ...this.baseData,
        addressInfo: this.addressInfo || null,
        pickSiteInfo: this.pickSiteInfo,
      }
    },
    // 是商家店铺小程序
    inLittleProgram() {
      // 先判断是不是小程序环境
      if (window.wx && window.wx.CLIENT_ENV === "wx_miniProgram") {
        if (this.isInElive) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    //IOS小程序端 ios小程序商品列表 直播、线下课、班课、实物商品可买，其他知识商品不可买，需不显示价格 点击去抢购后按现网逻辑跳转至小程序的商品详情
    isIOSMiniprogram() {
      return (
        window.wx &&
        window.wx.CLIENT_SYSTEM === "IOS" &&
        window.wx.CLIENT_ENV === "wx_miniProgram"
      );
    },
    isIosWxMiniProgramSDK() {
      return (
        window.wx &&
        window.wx.CLIENT_SYSTEM === "IOS" &&
        window.wx.CLIENT_ENV === "wx_program_wechat_sdk"
      );
    },
    IOSMiniProgramCanBuy() {
      return [4, 29, 35, 21, 69].indexOf(Number(this.goodsItem.resource_type)) > -1; //true-能买 false-不能买
    },
    // 是否为组合商品
    isCOPGoods(){
      return this.goodsItem.spu_type === COP_GOODS;
    },
    // 小程序环境下需要判断资质，其他环境默认为true
    littleProgramCategoryInfo() {
      if (this.inLittleProgram) {
        let needCategoryInfo = [21, 20, 7, 16, 69]; // 实物商品、电子书、打卡、圈子、组合商品需要判断资质
        if (
          needCategoryInfo.indexOf(this.goodsItem.resource_type) > -1 &&
          Array.isArray(this.categoryInfo)
        ) {
          return (
            this.categoryInfo.indexOf(Number(this.goodsItem.resource_type)) > -1
          );
        } else {
          return true;
        }
      } else {
        return true;
      }
    },
    //判断是不是鹅直播
    isInElive() {
      // 先判断是不是小程序环境
      if (window.wx && window.wx.CLIENT_ENV === "wx_miniProgram") {
        if (
          this.getQueryStrDecode("unique_type") &&
          this.getQueryStrDecode("unique_type") === "elive"
        ) {
          return true;
        } else {
          return false;
        }
        return false;
      }
    },
  },
  created() {
    console.log('owgLivePay.vue created');
  },
  mounted() {
    console.log('goin');
    // 获取小程序SDK支付设置
    this.initMiniprogramSdkPaySetting();
    // TODO vuex dispatch 缺失

    // 检查订单状态
    // this.checkOrderState(2);
  },
  methods: {
    payComplete() {
      this.$emit("payComplete");
    },
    toShowSku() {
      this.spuId = this.goodsItem.resource_id;
      this.showSku = true;
    },
    // 获取小程序SDK支付配置
    initMiniprogramSdkPaySetting() {
      console.log(isMiniProgramSdk,this.miniprogramSdkPaySetting.fetchEnd);
      // 小程序SDK环境下才需要请求
      if (isMiniProgramSdk && !this.miniprogramSdkPaySetting.fetchEnd) {
        return getMiniprogramSdkPaySetting().then((data) => {
          const {
            payment_switch,
            payment_page_url
          } = data;
          const miniprogramSdkPaySetting = {
            paymentSwitch: payment_switch,
            paymentPageUrl: payment_page_url,
            fetchEnd: true
          }
          this.miniprogramSdkPaySetting = miniprogramSdkPaySetting;
          return data;
        }).catch((data) => {
          // TODO 日志上报
          // this.$skynet.report({
          //   details: {
          //     keyword: 'onfirmOrderPage_index_initMiniprogramSdkPaySetting',
          //     msg: '获取小程序SDK支付配置捕获异常日志',
          //     anchor: 'getMiniprogramSdkPaySetting',
          //     data
          //   },
          //   level: LogLevel.ERROR,
          //   type: LogType.HTTP_ERROR
          // })
          // 接口出错，关闭支付
          const miniprogramSdkPaySetting = {
            paymentSwitch: MINIPROGRAM_SDK_PAY_SETTING.OFF,
            paymentPageUrl: '',
            fetchEnd: true
          }
          this.miniprogramSdkPaySetting = miniprogramSdkPaySetting
          return Promise.reject(data);
        })
      }
    },
    /**
     * type 1：查询订单状态，并跳转 2：显示支付确认弹框
     */
    checkOrderState(type = HANDLE_ORDER[0]) {
      const { paySuccessUrl, payFailUrl, order } = getOrderCache();
      console.log(paySuccessUrl, payFailUrl, order);
      if (order) {
        switch (type) {
          case HANDLE_ORDER[0]:
            new PayBackHandler(paySuccessUrl, payFailUrl, order).perform();
            break;
          case HANDLE_ORDER[1]:
            this.showConfirmBox = true;
            break;
          default:
            console.warn('checkOrderState type: ', type);
        }
      }
    },
    skuBuy(obj) {
      this.baseInfoQuery = obj;
      this.reportBaseInfo()
      this.showConfirmOrder = true;
    },
    buy: debounce(
      function (params,useScatter = false) {
        console.log('params',params);
        this.useScatter = useScatter;
        this.goodsItem = params.goodsItem;
        this.categoryInfo = params.categoryInfo;
        this.hasPreferentialPrice = params.hasPreferentialPrice;
        this.isFromLiveGoodsList = params.isFromLiveGoodsList || false;
        this.isToDetails = params.toDetails;
        this.alive_sub_id = params.alive_sub_id;
        this.permission = params.permission || false;
        this.checkPrice = params.checkPrice || (() => {});
        this.checkLogin();// 购买前判断登录态
      },
      1000,
      true
    ),
    // 埋点
    sensor() {
      if (this.isFromLiveGoodsList) {
        console.log("直播带货走当页支付路径的去抢购埋点");
        sensorsTrackButton({
          goods_id: this.goodsItem.id,
          spu_type: SPU_TYPE[Number(this.goodsItem.resource_type)] || this.goodsItem.spu_type,
          page_id: "C#h5#alive#alive_room",
          l_program: "H5",
          page_name: "直播间页面",
          page_path: "C端#H5#直播#直播间页面",
          page_button: "去抢购",
          app_id: this.aliveInfo.app_id,
          alive_sub_id: this.alive_sub_id,
          c_user_id: this.aliveInfo.user_id,
          client: window.wx?.CLIENT_SYSTEM,
          resource_id: this.goodsItem.resource_id,
          cmm2: window.isQlive ? "企业直播" : "知识店铺",
        })
      }
    },
    checkLogin() {
      this.inLittleProgram
        ? anonyLogon(this.getMoveRouter) // 前往登录
        : this.getMoveRouter(); // 当页支付
    },
    isMiniProgramSdkCanBuy(spuType) {
      return IOS_MINIPROGRAM_DISPLAY_TYPE.includes(spuType)
    },
    getMoveRouter() {
      let toDetails = this.isToDetails;
      this.sensor();
      this.$emit("buying");
      if (isIos && isELearnApp) {
        Toast(this.t("liveGoodsList_msg_notSupport"));
        return;
      }

      // 安卓app暂未接入支付流程与鹅直播内嵌特殊逻辑，店铺小程序没资质的情况弹窗，限制购买
      // ios小程序sdk限制直播、实物、服务类可购买
      if (
        (this.isAndroid && isELearnApp) ||
        !this.littleProgramCategoryInfo ||
        this.isInElive ||
        isMiniProgramSdk && isIos && !this.isMiniProgramSdkCanBuy(this.goodsItem.spu_type)
      ) {
        Toast.clear();
        this.showCopyModal();
        return;
      }
      //线下课 课时包；拼团活动；IOS小程序不能买，点击热区，免费领取，去详情页
      if (
        ([29,42].indexOf(Number(this.goodsItem.resource_type)) > -1 ||
          [6].indexOf(Number(this.goodsItem.activity_type)) > -1 ||
          ((this.isIOSMiniprogram || this.isIosWxMiniProgramSDK) && !this.IOSMiniProgramCanBuy) ||
          toDetails) && !this.isLiveH5
      ) {
        this.judgePermission(this.permission) // 判断权益，免费领取-有权益 弹窗
        return;
      }

      this.setSessionStorage();

      let params = {
        id: this.goodsItem.id,
        resource_id: this.goodsItem.resource_id,
        resource_type: Number(this.goodsItem.resource_type),
        price: this.goodsItem.price,
        app_id: window.APPID,
        user_id: window.USERID,
        alive_id: this.aliveInfo.alive_id,
      };
      request({
        // 在灰度内就用新接口
        url: this.isGrayMarketing ? "/xe.transact.check.snap_up/3.0.1" : "/_alive/xe.ecommerce.alive_goods_system.check.snap_up/1.0.0",
        params,
        requestType:this.isGrayMarketing ? 'json' : 'form'
      })
        .then((res) => {
          Toast.clear();
          let { code, data } = res;
          if (code === 0) {
            if (data.err_msg) {
              Toast(data.err_msg);
            }
            if (data.is_sec_kill_toast) {
              Toast(this.t("liveGoodsList_msg_isSecondKill"));
            }

            // 直播跳转详情页需判断权益  线下课 课时包；拼团活动；IOS小程序不能买，点击热区，免费领取，去详情页否则提示弹窗
            if (
              data.is_goods_detail === 1 ||
              ([29, 42].indexOf(Number(this.goodsItem.resource_type)) > -1 ||
                [6].indexOf(Number(this.goodsItem.activity_type)) > -1 ||
                (this.isIOSMiniprogram && !this.IOSMiniProgramCanBuy) ||
                toDetails) && this.isLiveH5
            ) {
              // 去详情页，判断权益
              this.judgePermission(data.is_has_permission)
            } else if (data.is_more_sku === 1) {
              // 矫正价格
              this.checkPrice(this.isToDetails)
              this.toShowSku();
            } else {
              // 矫正价格
              this.checkPrice(this.isToDetails)
              this.toShowConfirmOrder(data.sku);
            }
          } else {
            Toast(this.t("msg_networkBusy"));
          }
        })
        .catch((err) => {
          Toast(this.t("msg_networkBusy"));
        });
    },
    toShowConfirmOrder(sku) {
      //带货列表返回的 resource_id就是业务侧的spu_id
      // 返回的id,就是业务侧的resource_id
      let params = {
        id: this.goodsItem.resource_id,
        spu_id: this.goodsItem.resource_id,
        resource_type: Number(this.goodsItem.resource_type),
        resource_id: this.goodsItem.id,
        spu_type: SPU_TYPE[Number(this.goodsItem.resource_type)] || this.goodsItem.spu_type,
        sku,
        count: 1,
        isAlive: 1,
        hasPreferentialPrice: this.hasPreferentialPrice, // 有券后价，去确认订单领取优惠券
        aliveId: this.aliveInfo.alive_id,
        superVipPrice: this.goodsItem.svip_price,
        price: this.goodsItem.price
      };
      this.baseInfoQuery = params;
      this.reportBaseInfo()
      console.log('go in',this.baseInfoQuery);
      this.showConfirmOrder = true;
    },
    reportBaseInfo(){
      this.$skynet.report({
        details: {
          keyword: 'baseInfoQuery_assemble',
          msg: 'baseInfoQuery',
          baseInfoQuery: this.baseInfoQuery
        },
        level: LogLevel.ERROR,
        type: LogType.HTTP_ERROR
      })
    },
    getQueryStrDecode: (key) => {
      let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
      let r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return decodeURI(r[2]);
      }
      return null;
    },
    // 支付成功
    successCallback(payResult) {
      console.log("支付成功: ", payResult);
      this.payCompleteQuery = {
        ...this.baseInfoQuery,
        ...payResult,
      };
      console.log("支付成功1: ", this.payCompleteQuery);
      this.showConfirmOrder = false;
      this.showPayComplete = true;
      this.showSku = false;
    },
    // 支付失败
    failCallback() {
      console.log("支付失败");
      this.showConfirmOrder = false;
      this.showSku = false;
      this.$emit("failCallback", !this.refresh);
    },
    // 显示复制链接弹框
    showCopyModal() {
      // 拼接 aliveId 记录直播带货订单，避免直播信息参数丢失导致没有记录为直播带货订单
      let jumpUrl = `${this.goodsItem.target_url}&aliveId=${this.aliveInfo.alive_id}`
      let that = this;
      let showCopyText =
        this.isAndroid && this.isXiaoEHelperApp
          ? this.t("liveGoodsList_msg_paymentNotSupportApp")
          : this.t("liveGoodsList_msg_paymentNotSupportMp");
      Dialog.confirm({
        closeOnClickOverlay: true,
        message: showCopyText,
        confirmButtonText: this.t("liveGoodsList_copyLink"),
        cancelButtonText: this.t("liveGoodsList_has_product_no"),
        confirmButtonColor: "#1472FF",
        className: `conlinDialog`,
        overlayClass: "conlinOverlay",
        getContainer: this.getContainer // 全屏状态挂载到全屏组件下
      }).then(() => {
        that.copy(jumpUrl, () => {
          setTimeout(() => {
            Toast(this.t("liveGoodsList_msg_copyLink"));
          }, 200);
        });
      });
    },
    copy(content, cb = () => {}) {
      var aux = document.createElement("input");
      aux.setAttribute("value", content);
      document.body.appendChild(aux);
      aux.select();
      const status = document.execCommand("copy");
      document.body.removeChild(aux);
      if (status) {
        console.log("复制成功");
        cb();
      } else {
        console.log("复制失败");
      }
    },
    judgePermission(Permission){
      if(Permission){
        // 权益提示弹窗
        this.showDetailDialog()
      }else{
        this.gotoDetails()
      }
    },
    showDetailDialog(){
      let that = this
      Dialog.confirm({
        closeOnClickOverlay: true,
        message: this.t("liveGoodsList_has_product"),
        confirmButtonText: this.t("liveGoodsList_has_product_yes"),
        cancelButtonText: this.t("liveGoodsList_has_product_no"),
        confirmButtonColor: "#1472FF",
        className: `conlinDialog`,
        overlayClass: "conlinOverlay",
        getContainer: this.getContainer // 全屏状态挂载到全屏组件下
      }).then(() => {
        that.gotoDetails(true)
      });
    },
    gotoDetails(toH5Details) {
      let aliveBackUrl = this.setSessionStorage();

      //跳转链接 带上参数
      let url = this.goodsItem.target_url;
      let jumpUrl = this.goodsItem.target_url, //跳转链接
        queryIndex = url.indexOf("?"); //查询索引位置

      if (queryIndex === -1) {
        jumpUrl += "?"; //问号不存在，则拼接问号
      } else {
        url.length - 1 !== queryIndex ? (jumpUrl += "&") : ""; //问号是否不在末尾位置? 进行&拼接 ：不处理
      }

      jumpUrl = `${jumpUrl}live_room=1&success=1&aliveId=${this.aliveInfo.alive_id}&aliveBackUrl=${aliveBackUrl}`;
      if (![0, 2, 3].includes(this.aliveInfo.alive_state)) {
        jumpUrl += `&is_living=1`;
      }

      if (this.inLittleProgram) {
        this.miniprogramToDetails(jumpUrl);
      } else {
        this.isLiveH5 && !toH5Details?this.$emit('toH5Details', urlConcatParams(jumpUrl)):this.toH5Details(jumpUrl);
      }
    },
    toH5Details(jumpUrl) {
      // window.location.href = jumpUrl;
      jumpTool.jumpTargetUrl({url: jumpUrl});
    },
    setSessionStorage() {
      //处理缓存，可能在跳出直播间后，下单、支付完成页回调用到
      const refResId = this.goodsItem.resource_id;
      const refResType = this.goodsItem.resource_type;
      let aliveBackUrl = window.location.href;
      // 拼接上带货标注与带货商品信息，带货回到直播间可显示对应商品的引导加群与支付信息
      if (aliveBackUrl.indexOf("?") !== -1) {
        aliveBackUrl = `${aliveBackUrl}&success=1&isCommerceBack=1&refResId=${refResId}&refResType=${refResType}`;
      } else {
        aliveBackUrl = `${aliveBackUrl}?success=1&isCommerceBack=1&refResId=${refResId}&refResType=${refResType}`;
      }
      if (this.getQueryStrDecode("order_id")) {
        aliveBackUrl = this.delUrlParam(aliveBackUrl, "order_id");
      }
      sessionStorage.setItem("aliveBackUrl", aliveBackUrl);
      sessionStorage.setItem("aliveId", this.aliveInfo.alive_id);
      return encodeURIComponent(aliveBackUrl);
    },
    // 删除url中所携带的参数
    delUrlParam(url, paramKey) {
      const urlObj = new URL(url);
      let urlParam = urlObj.search.substr(1);
      let beforeUrl = url.substr(0, url.indexOf("?"));
      let nextUrl = "";

      let arr = new Array();
      if (urlParam != "") {
        let urlParamArr = urlParam.split("&");
        for (let i = 0; i < urlParamArr.length; i++) {
          let paramArr = urlParamArr[i].split("=");
          if (paramArr[0] != paramKey) {
            arr.push(urlParamArr[i]);
          }
        }
      }
      if (arr.length > 0) {
        nextUrl = "?" + arr.join("&");
      }
      url = beforeUrl + nextUrl;
      return url;
    },
    //小程序跳商品详情
    miniprogramToDetails(jumpUrl) {
      let h5_url = encodeURIComponent(jumpUrl);
      if (this.goodsItem.resource_type == 21) {
        //实物商品
        let search = `id=${this.goodsItem.id}&h5Url=${h5_url}&__id__=1`;
        wx &&
        wx.miniProgram.navigateTo({
          url:
            "/packageCommodity/page/content_entity_goods/content_entity_goods?" +
            search,
        });
      } else if (this.goodsItem.resource_type == 2) {
        //音频
        let search = `id=${this.goodsItem.id}&h5Url=${h5_url}&__id__=2`;
        wx &&
        wx.miniProgram.navigateTo({
          url: "/page/home/content/content_audio/content_audio?" + search,
        });
      } else if (this.goodsItem.resource_type == 3) {
        //视频
        let search = `id=${this.goodsItem.id}&h5Url=${h5_url}&__id__=3`;
        wx &&
        wx.miniProgram.navigateTo({
          url: "/page/home/content/content_video/content_video?" + search,
        });
      } else {
        window.location.href = jumpUrl;
      }
    },
    // 关闭弹框
    closePop() {
      // this.$emit("update:open", false);
    },
    // 返回箭头点击事件
    backClick() {
      // TODO 返回上一页
      // this.$refs.confirmOrderRef.backClick();
    },
  }
}
</script>
